<?php
/**
 * Created by PhpStorm.
 * User: smilezheng
 * Date: 2019/9/9
 * Time: 16:15
 */

namespace App\Service;

use App\Entity\KeyValues;
use Doctrine\ORM\EntityManagerInterface;

class SaveInfoService
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * SaveInfoService constructor.
     *
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @param string $key
     * @param string $value value 可以为各种
     *
     * @return int
     */
    public function saveValues(?string $key, ?string $value): int
    {
        if ($key == null) {
            return 0;
        }
        $keyValues = new KeyValues();
        $keyValues->setValue($value)
            ->setKeyName($key);
        $this->em->persist($keyValues);
        $this->em->flush();
        return $keyValues->getId();
    }

    /**
     * @param string $id
     *
     * @return array|null
     */
    public function getValueById(string $id): ?array
    {
        $keyValue = $this->em->getRepository(KeyValues::class)->find($id);
        if ($keyValue === null) {
            return null;
        }
        assert($keyValue instanceof KeyValues);
        return [
            'id'    => $keyValue->getId(),
            'key'   => $keyValue->getKeyName(),
            'value' => $keyValue->getValue()
        ];
    }

    /**
     * @param string $key
     *
     * @return array|null
     */
    public function getValueByKey(string $key): ?array
    {
        $qb = $this->em->createQueryBuilder()
            ->select(['k.id', 'k.keyName as key', 'k.value'])
            ->from(KeyValues::class, 'k')
            ->where('k.keyName = :key')
            ->setParameter(':key', $key)
            ->orderBy('k.id', 'desc')
            ->setMaxResults(1);
        return $qb->getQuery()->getResult()[0] ?? null;
    }
}